package com.training.api.controller;

import com.training.api.service.ClientKeyService;
import com.training.base.Result;
import com.training.bean.ClientPublicKey;
import com.training.jwt.JWTUtils;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/key")
public class ClientKeyController {
    
    @Autowired
    private ClientKeyService clientKeyService;
    
    /**
     * 客户端上传公钥
     * @param publicKey Base64编码的公钥
     * @return 操作结果
     */
    @PostMapping("/uploadPublicKey")
    public ResponseEntity<Result<String>> uploadPublicKey(@RequestParam String publicKey,HttpServletRequest request) {
        try {
            // 从JWT token中获取用户ID
            int uid = JWTUtils.getUserIdFromRequest(request);
            clientKeyService.saveClientPublicKey(uid, publicKey);
            String aesKey = clientKeyService.generateAndEncryptAESKey(uid);
            return ResponseEntity.ok(new Result<>(aesKey, true, "更新key成功"));
        } catch (Exception e) {
            e.printStackTrace();
             return ResponseEntity.status(500).body(Result.fail(500, e.getMessage()));
        }
    }
    
    /**
     * 获取加密后的AES密钥
     * @return 加密后的AES密钥
     */
    @GetMapping("/getEncryptedAESKey")
    public ResponseEntity<Result<String>> getEncryptedAESKey(HttpServletRequest request) {
        try {
            // 从JWT token中获取用户ID
            int uid = JWTUtils.getUserIdFromRequest(request);
            String encryptedAESKey = clientKeyService.generateAndEncryptAESKey(uid);
            return ResponseEntity.ok(new Result<>(encryptedAESKey, true, "获取加密AES密钥成功"));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body(Result.fail(500, e.getMessage()));
        }
    }
}